package org.agent.aigccore.basic.serializable;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.OffsetDateTime;
import java.time.ZoneId;

/**
 * OffsetDateTime类型处理器
 * 用于MyBatis处理OffsetDateTime与数据库TIMESTAMPTZ的转换
 */
@MappedTypes(OffsetDateTime.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class OffsetDateTimeTypeHandler extends BaseTypeHandler<OffsetDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, OffsetDateTime parameter, JdbcType jdbcType) throws SQLException {
        // 将OffsetDateTime转换为Timestamp存储
        // PostgreSQL的TIMESTAMPTZ会自动处理时区信息
        if (jdbcType == null) {
            ps.setObject(i, Timestamp.from(parameter.toInstant()), Types.TIMESTAMP_WITH_TIMEZONE);
        } else {
            ps.setObject(i, Timestamp.from(parameter.toInstant()), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return timestamp != null ? OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("Asia/Shanghai")) : null;
    }

    @Override
    public OffsetDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        return timestamp != null ? OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("Asia/Shanghai")) : null;
    }

    @Override
    public OffsetDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        return timestamp != null ? OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("Asia/Shanghai")) : null;
    }
}
